<template>
	<view class="campus-page">
		<nav-header title="校园经历"></nav-header>

		<view class="content" :style="{ marginTop: statusBarHeight + 44 + 'px' }">
			<view class="page-title">校园经历</view>
			<view class="subtitle">填写你参与的学生组织、社团活动、竞赛经历等</view>

			<!-- Experience Name Field -->
			<view class="form-item">
				<text class="label required">经历名称</text>
				<input class="input" type="text" placeholder="请输入经历名称" v-model="formData.experienceName" />
			</view>

			<!-- Role Field -->
			<view class="form-item">
				<text class="label required">担任职务</text>
				<input class="input" type="text" placeholder="请输入职务名称" v-model="formData.position" />
			</view>

			<!-- Time Period -->
			<view class="form-item">
				<text class="label required">时间段</text>
				<view class="time-range">
					<!-- Start Time -->
					<picker mode="date" :value="formData.startDate" fields="month" @change="handleStartTimeChange">
						<view class="time-picker">
							<text>{{ formData.startDate ? formData.startDate : '开始时间' }}</text>
							<text class="picker-arrow">▼</text>
						</view>
					</picker>

					<text class="time-separator">至</text>

					<!-- End Time -->
					<picker mode="date" :value="formData.endDate" fields="month" @change="handleEndTimeChange">
						<view class="time-picker">
							<text>{{ formData.endDate && formData.endDate !== '至今' ? formData.endDate : '结束时间' }}</text>
							<text class="picker-arrow">▼</text>
						</view>
					</picker>
				</view>
			</view>

			<!-- Description -->
			<view class="form-item">
				<view style="display: flex;justify-content: space-between;align-items: center;margin-bottom: 10px;">
					<text class="label">经历描述</text>
					<button class="generate-btn" @click="generateCampus">
							<text class="generate-icon">✨</text>
							AI生成
						</button>
				</view>
				<textarea class="textarea"
					placeholder="可填写在校参与的学生组织、社团活动、学生会职务、班干职务、竞赛经历，例：学生会干部、学习委员、创新创业大赛。重点强调个人职责和成果。如果不填则由AI根据经历自动撰写。"
					v-model="formData.experienceDescription" maxlength="500"></textarea>
				<text class="word-count">{{ formData.experienceDescription ? formData.experienceDescription.length : 0 }}/500</text>
			</view>
		</view>

		<view class="bottom">
			<!-- Delete Button -->
			<view class="delete-action" v-if="!isAdding">
				<button class="delete-btn" @click="confirmDelete">删除</button>
			</view>

			<!-- Save Button (Fixed at Bottom) -->
			<view class="action-bar">
				<button class="save-btn" @click="saveCampus">保存</button>
			</view>
		</view>

		<!-- Delete Confirmation -->
		<uni-popup ref="deleteConfirmPopup" type="dialog">
			<uni-popup-dialog title="删除确认" content="确定要删除这条校园经历吗？删除后将无法恢复。" :beforeClose="true"
				@confirm="deleteCampusExp" @close="closeDeletePopup"></uni-popup-dialog>
		</uni-popup>
		<view>
			<!-- 普通弹窗 -->
			<uni-popup ref="popupCampus" background-color="#fff" mask-background-color="rgba(0,0,0,0)"
				:is-mask-click="false" type="bottom" borderRadius='20px 20px 0 0 '>
				<view class="popup-content">
					<view class="popup-header">
						<text class="popup-title">AI生成</text>
						<uni-icons type="closeempty" size="24" @click="closePopupCampus"></uni-icons>
					</view>
					<view class="popup-body">
						<text>{{AIContent}}</text>
					</view>
					<view class="popup-footer">
						<button class="popup-btn" @click="rewriteCampus">重写</button>
						<button type="primary" class="popup-btn" @click="replaceCampus">替换</button>
					</view>
				</view>
			</uni-popup>
		</view>
	</view>
</template>

<script setup>
	import {
		ref,
		reactive,
		onMounted,
		watch,
		nextTick
	} from 'vue'
	import NavHeader from '@/components/nav-header.vue'
	import {
		onLoad,
		onUnload
	} from '@dcloudio/uni-app'
	import {
		getCampusExperienceList,
		getCampusExperienceDetail,
		addCampusExperience,
		updateCampusExperience,
		deleteCampusExperience,
		generateCampusExperienceDescription
	} from '@/api/edit/campus'
	import {
		useResumeStore
	} from '@/store/resume.js'
	import env from '@/env'
	import { useAuthStore } from '@/store/index';
	import { mockInterviewWebSocketProcess } from '@/api/ai'
	import { useWebSocket } from '@/utils/useWebSocket'
	
	const authStore = useAuthStore();
	const statusBarHeight = ref(20)
	const deleteConfirmPopup = ref(null)
	const { messages, isConnected, connect, sendMessage, close, onMessage } = useWebSocket(env.websocket)

	const isAdding = ref(true)
	const currentId = ref(null)
	const currentYear = new Date().getFullYear()
	
	const formData = reactive({
		experienceName: '',
		position: '',
		startDate: '',
		endDate: '',
		experienceDescription: ''
	})
	const resumeStore = useResumeStore()
	const popupCampus = ref(null)
	const AIContent = ref('')
	const isGenerating = ref(false)

	// 注册WebSocket消息处理函数
	onMessage((data) => {
		uni.hideLoading();
		try {
			if (JSON.parse(data).topic === 'CAMPUS_EXPERIENCE') {
				if (JSON.parse(data).content === '[DONE]' || JSON.parse(data).content.includes('[DONE]')) {
					isGenerating.value = false;
					uni.hideLoading();
					uni.showToast({
						title: '生成完成',
						icon: 'success'
					});
					return;
				}
				AIContent.value += JSON.parse(data).content;
				return;
			}
		} catch (error) {
			console.error('处理WebSocket消息出错:', error);
		}
	});

	onLoad(async (options) => {
		console.log('啊啊啊：',options);
		if (options.index) {
			// 编辑模式，获取详情
			isAdding.value = false
			currentId.value = options.index
			await fetchCampusDetail(options.index)
		} else {
			isAdding.value = true
			resetForm()
		}
	})

	onMounted(() => {
		const systemInfo = uni.getSystemInfoSync()
		statusBarHeight.value = systemInfo.statusBarHeight
		
		// 启动时先尝试连接WebSocket
		try {
			connect().then(() => {
				console.log('WebSocket连接成功，可以接收消息');
			}).catch(err => {
				console.error('WebSocket连接失败:', err);
			});
		} catch (e) {
			console.error('连接WebSocket异常:', e);
		}
	})

	onUnload(() => {
		// 关闭WebSocket连接
		close();
		if (isGenerating.value) {
			isGenerating.value = false;
		}
	});

	function resetForm() {
		formData.experienceName = ''
		formData.position = ''
		formData.startDate = ''
		formData.endDate = ''
		formData.experienceDescription = ''
	}

	async function fetchCampusDetail(id) {
		try {
			uni.showLoading({
				title: '加载中...'
			})
			const res = await getCampusExperienceDetail(id)
			if (res.code === 200 && res.data) {
				Object.assign(formData, res.data)
			}
		} catch (e) {
			uni.showToast({
				title: '加载失败',
				icon: 'none'
			})
		} finally {
			uni.hideLoading()
		}
	}

	const handleStartTimeChange = (e) => {
		formData.startDate = e.detail.value
	}
	const handleEndTimeChange = (e) => {
		formData.endDate = e.detail.value
	}

	const saveCampus = async () => {
		if (!formData.experienceName) {
			uni.showToast({
				title: '请输入经历名称',
				icon: 'none'
			});
			return
		}
		if (!formData.position) {
			uni.showToast({
				title: '请输入担任职务',
				icon: 'none'
			});
			return
		}
		if (!formData.startDate) {
			uni.showToast({
				title: '请选择开始时间',
				icon: 'none'
			});
			return
		}
		if (formData.startDate && formData.endDate) {
			const startParts = formData.startDate.split('.')
			const endParts = formData.endDate.split('.')
			const startYear = parseInt(startParts[0])
			const startMonth = parseInt(startParts[1])
			const endYear = parseInt(endParts[0])
			const endMonth = parseInt(endParts[1])
			if (endYear < startYear || (endYear === startYear && endMonth < startMonth)) {
				uni.showToast({
					title: '结束时间不能早于开始时间',
					icon: 'none'
				});
				return
			}
		}
		try {
			uni.showLoading({
				title: '保存中...'
			})
			let res
			const params = {
				...formData,
				resumeId: resumeStore.resumeId
			}
			if (isAdding.value) {
				res = await addCampusExperience(params)
			} else {
				params.id = currentId.value
				res = await updateCampusExperience(params)
			}
			if (res.code === 200) {
				uni.showToast({
					title: isAdding.value ? '添加成功' : '更新成功',
					icon: 'success'
				})
				setTimeout(() => {
					uni.navigateBack()
				}, 1500)
			} else {
				uni.showToast({
					title: res.msg || '保存失败',
					icon: 'none'
				})
			}
		} catch (e) {
			uni.showToast({
				title: '保存失败',
				icon: 'none'
			})
		} finally {
			uni.hideLoading()
		}
	}

	const closeDeletePopup = () => {
		deleteConfirmPopup.value.close()
	}
	
	const confirmDelete = () => {
		deleteConfirmPopup.value.open()
	}
	
	const deleteCampusExp = async () => {
		if (!currentId.value) return
		try {
			uni.showLoading({
				title: '删除中...'
			})
			const res = await deleteCampusExperience(currentId.value)
			if (res.code === 200) {
				uni.showToast({
					title: '删除成功',
					icon: 'success'
				})
				setTimeout(() => {
					uni.navigateBack()
				}, 1500)
			} else {
				uni.showToast({
					title: res.msg || '删除失败',
					icon: 'none'
				})
			}
		} catch (e) {
			uni.showToast({
				title: '删除失败',
				icon: 'none'
			})
		} finally {
			uni.hideLoading()
		}
	}

	// 使用AI生成校园经历
	const generateCampus = async () => {
		try {
			// 避免重复请求
			if (isGenerating.value) {
				return;
			}
			
			isGenerating.value = true;
			AIContent.value = ''; // 清空之前的内容
			popupCampus.value.open();
			
			uni.showLoading({
				title: 'AI生成中...'
			});
			
			// 创建请求数据
			const requestData = {
				type: 'CAMPUS_EXPERIENCE',
				aiResumeCampusExperienceBo: {
					resumeId: resumeStore.resumeId,
					experienceName: formData.experienceName,
					position: formData.position,
					startDate: formData.startDate,
					endDate: formData.endDate
				}
			};
			
			
			// 检查WebSocket连接状态
			if (!isConnected.value) {
				console.log('WebSocket未连接，尝试连接...');
				await connect();
				console.log('WebSocket连接已建立');
			} else {
				console.log('WebSocket已连接，状态正常');
			}
			
			// 确保WebSocket已连接后，调用HTTP接口触发后端推送消息
			console.log('准备调用HTTP接口触发后端推送...');
			
			// 调用HTTP接口触发后端推送WebSocket消息
			// 1. 先调用HTTP接口，但不处理响应，依靠WebSocket接收消息
			// 2. WebSocket消息处理由onMessage回调函数处理
			mockInterviewWebSocketProcess(requestData).then(res => {
				// 如果很长时间没收到WebSocket消息，可能后端未正确推送，此时使用HTTP响应结果
				setTimeout(() => {
					if (isGenerating.value && AIContent.value === '') {
						console.log('未收到WebSocket消息，使用HTTP响应结果');
						try {
							isGenerating.value = false;
							// uni.hideLoading();
							// uni.showToast({
							// 	title: '生成成功',
							// 	icon: 'success'
							// });
						} catch (err) {
							console.error('处理HTTP响应失败:', err);
						}
					}
				}, 5000); // 5秒后检查
				
			}).catch(err => {
				console.error('调用HTTP接口失败:', err);
				uni.hideLoading();
				isGenerating.value = false;
				uni.showToast({
					title: '生成失败',
					icon: 'none'
				});
			});
			
		} catch (e) {
			console.error('生成校园经历失败:', typeof e === 'object' ? JSON.stringify(e) : e);
			uni.hideLoading();
			isGenerating.value = false;
			uni.showToast({
				title: 'AI生成失败: ' + (e.message || '未知错误'),
				icon: 'none'
			});
		}
	};

	// 关闭AI生成弹窗
	const closePopupCampus = () => {
		popupCampus.value.close();
		uni.hideLoading();
		isGenerating.value = false;
	};

	// 重写AI生成内容
	const rewriteCampus = () => {
		// 确保上一次生成已经结束
		isGenerating.value = false;
		setTimeout(() => {
			generateCampus();
		}, 300);
	};

	// 替换AI生成内容
	const replaceCampus = () => {
		popupCampus.value.close();
		formData.experienceDescription = AIContent.value;
		isGenerating.value = false;
	};
</script>

<style lang="scss" scoped>
	.campus-page {
		min-height: 100vh;
		background-color: #ffffff;
		padding-bottom: 70px;

		.content {
			padding: 20px;

			.page-title {
				font-size: 24px;
				font-weight: bold;
				color: #333;
				margin-bottom: 6px;
			}

			.subtitle {
				font-size: 14px;
				color: #999;
				margin-bottom: 24px;
			}

			.form-item {
				margin-bottom: 24px;
				position: relative;

				.label {
					font-size: 16px;
					color: #333;
					margin-bottom: 10px;
					display: block;
					font-weight: 500;

					&.required:after {
						content: '*';
						color: #ff4d4f;
						margin-left: 4px;
					}
				}

				.input {
					height: 44px;
					line-height: 44px;
					border-bottom: 1px solid #e5e5e5;
					font-size: 16px;
					color: #333;
					background-color: #f6f8fa;
					border-radius: 8px;
					padding: 0 12px;

					&.picker {
						display: flex;
						align-items: center;
						justify-content: space-between;

						.placeholder {
							color: #999;
						}
					}

					&.disabled {
						color: #666;
					}
				}

				.paste-btn {
					position: absolute;
					right: 0;
					top: 8px;
					background-color: #f6f6f6;
					color: #666;
					font-size: 12px;
					padding: 4px 8px;
					border-radius: 4px;
					line-height: 1.2;
					border: none;
				}

				.time-range {
					display: flex;
					align-items: center;
					justify-content: space-around;

					.time-picker {
						flex: 1;
						height: 44px;
						padding: 0 12px;
						background-color: #f6f8fa;
						border-radius: 8px;
						display: flex;
						align-items: center;
						justify-content: space-between;
						font-size: 16px;
						color: #333;

						&.disabled {
							color: #666;
							opacity: 0.7;
						}

						.placeholder {
							color: #999;
						}

						.picker-arrow {
							margin-left: 4px;
							font-size: 12px;
							color: #999;
						}
					}

					.time-separator {
						margin: 0 15px;
						color: #666;
					}
				}

				.current-switch {
					display: flex;
					align-items: center;
					justify-content: flex-end;
					margin-top: 10px;

					text {
						font-size: 14px;
						color: #666;
						margin-right: 8px;
					}
				}

				.textarea {
					height: 120px;
					border: 1px solid #e5e5e5;
					border-radius: 8px;
					padding: 12px;
					font-size: 15px;
					color: #333;
					background-color: #f6f8fa;
				}

				.word-count {
					font-size: 12px;
					color: #999;
					position: absolute;
					right: 10px;
					bottom: -20px;
				}

				.ai-btn {
					position: absolute;
					right: 10px;
					top: 10px;
					background-color: #f0f7ff;
					color: #4080ff;
					padding: 4px 10px;
					border-radius: 16px;
					font-size: 12px;

					&::before {
						content: '✨';
						margin-right: 2px;
					}
				}
			}
		}

		.bottom {
			position: fixed;
			bottom: 0;
			left: 0;
			right: 0;
			height: 70px;
			background-color: #fff;
			display: flex;
			align-items: center;
			justify-content: center;
			padding: 0 20px;
			box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.05);
			z-index: 9;
			gap: 30rpx;
		}

		.delete-action {
			.delete-btn {
				width: 100%;
				height: 44px;
				line-height: 44px;
				text-align: center;
				border-radius: 22px;
				font-size: 16px;
				color: #ff4d4f;
				background-color: #fff;
				border: 1px solid #ff4d4f;
			}
		}

		.action-bar {
			flex: 1;

			.save-btn {
				width: 100%;
				height: 44px;
				line-height: 44px;
				background-color: #5ac725;
				color: #FFFFFF;
				font-size: 16px;
				font-weight: 500;
				border-radius: 22px;
			}
		}

		.picker-popup {
			background-color: #fff;
			border-radius: 12px 12px 0 0;
			overflow: hidden;

			.picker-header {
				display: flex;
				align-items: center;
				justify-content: space-between;
				padding: 12px 16px;
				border-bottom: 1px solid #f0f0f0;

				.title {
					font-size: 16px;
					color: #333;
				}

				.cancel-btn {
					font-size: 15px;
					color: #999;
				}

				.confirm-btn {
					font-size: 15px;
					color: #5ac725;
				}
			}

			.picker-view {
				width: 100%;
				height: 240px;

				.picker-item {
					line-height: 36px;
					text-align: center;
					font-size: 16px;
				}
			}
		}
	}
</style>